package com.zyylc.wine.util;

import java.text.SimpleDateFormat;

import java.text.ParseException;

import java.util.Date;

/**
 * 身份证号验证工具类
 * @author lik
 */
public class IdentityCheckUtil {

    //位权值数组
    private static byte[] Wi=new byte[17];
    //身份证前部分字符数
    private static final byte fPart = 6;
    //身份证算法求模关键值
    private static final byte fMod = 11;
    //旧身份证长度
    private static final byte oldIDLen = 15;
    //新身份证长度
    private static final byte newIDLen = 18;
    //新身份证年份标志
    private static final String yearFlag = "19";
    //校验码串 
    private static final String CheckCode="10X98765432"; 

    private static void setWiBuffer(){
        for(int i=0;i<Wi.length;i++){    
            int k = (int) Math.pow(2, (Wi.length-i));
            Wi[i] = (byte)(k % fMod);
        }
    }
    
    //获取新身份证的校验码
    private static String getCheckFlag(String idCard){
        int sum = 0;
        //进行加权求和 
        for(int i=0; i<17; i++){        
            sum += Integer.parseInt(idCard.substring(i,i+1)) * Wi[i];
        }
        //取模运算，得到模值
        byte iCode = (byte) (sum % fMod); 
        return CheckCode.substring(iCode,iCode+1);
    }

    //获取时间串
    private static String getIDDate(final String idCard,boolean newIDFlag){
        String dateStr = "";
        if(newIDFlag)
            dateStr = idCard.substring(fPart,fPart+8);
        else
            dateStr = yearFlag + idCard.substring(fPart,fPart+6);
        return dateStr;
    }

    //判断时间合法性
    private static boolean checkDate(final String dateSource){
        String dateStr = dateSource.substring(0,4)+"-"+dateSource.substring(4,6)+"-"+dateSource.substring(6,8);
        System.out.println(dateStr);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
        	format.setLenient(false);
            Date date= format.parse(dateStr);
            return (date!=null);
        } catch (ParseException e) {
            return false;
        }
    }

    //判断身份证号码的合法性
    public static boolean checkIDCard(final String idCard){
        //初始化方法
    	IdentityCheckUtil.setWiBuffer();
        if (idCard.length() != oldIDLen && idCard.length() != newIDLen){
            return false;
        }
        boolean isNew = (idCard.length() == newIDLen);
        String idDate = getIDDate(idCard, isNew);
        System.out.println(idDate);
        if(!checkDate(idDate)){
            return false;
        }
        if(isNew){//校验位
            String checkFlag = getCheckFlag(idCard);
            System.out.println(checkFlag);
            String theFlag = idCard.substring(idCard.length()-1,idCard.length());
            if(!checkFlag.equals(theFlag)){
                return false;
            }
        }
        return true;
    }

}
